#include "ThreadTemplate.hpp"
// #include "Thread.hpp"
#include <vector>
#include <unistd.h>
#include "Mutex.hpp"
// //全局
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int ticknumber = 1000;
struct ThreadData{
    string _name;
    ThreadData(string& name,Mutex* mutex):_name(name),_mutex(mutex){}
    Mutex* _mutex;
};
void ticket(ThreadData& data){
    while(1){
        {
            LockGuard lock(*(data._mutex));
            if (ticknumber > 0){
                usleep(1000);
                cout << data._name << " get a ticket, ticket numbers is: " << ticknumber << endl;
                ticknumber--;
            }
            else {
                //当前进程不用了记得释放锁
                break;
            }
        }
        // data._mutex->Lock();
        // if (ticknumber > 0){
        //     usleep(1000);
        //     cout << data._name << " get a ticket, ticket numbers is: " << ticknumber << endl;
        //     ticknumber--;
        //     data._mutex->Unlock();
        // }
        // else {
        //     //当前进程不用了记得释放锁
        //     data._mutex->Unlock();
        //     break;
        // }
    }
}
int main(){
    //局部锁
    vector<Thread<ThreadData>> _threads;
    Mutex mutex;
    for (int i =0; i< 5; i++){
        string name = "thread-" + to_string(i);
        ThreadData t(name,&mutex);
        _threads.emplace_back(ticket,t);
    }

    for (auto& t : _threads){
        t.Start();
    }
    
    sleep(5);
    for (auto& t : _threads){
        t.Stop();
    }

    for (auto& t : _threads){
        t.Join();
    }    


    return 0;
}